#!/usr/bin/perl -w

###############################################################################
# Create a database and the database schema.
#
# Parameters needed: dbname, username, temp_dir
#
# Author: Herodotos Herodotou and Nedyalko Borisov
# Date: March 11, 2010
#
##############################################################################

chdir("./src"); # Change the execution directory to src
use lib './src'; # Specify the library location
use getOpts qw(get_options println);

if ($#ARGV != 0)
{
   println qq(Please specify the .properties file);
   println qq(Usage: perl $0 create.properties);
   exit(-1);
}

# Get input parameters
%opt = get_options($ARGV[0]);
$DB_NAME  = $opt{'dbname'};
$USERNAME = $opt{'username'};
$TEMP_DIR = $opt{'temp_dir'};

# Ask for confirmation
println "This script will drop database $DB_NAME if it exists";
print "Are you sure (yes/no): ";

$| = 1;
$_ = <STDIN>;
chomp;

if ( $_ ne "yes" )
{
   exit(0);
}

# Create the temp directory
if (! -d "$TEMP_DIR")
{
   mkdir $TEMP_DIR or die $!;
}

# Create the database
println "Creating database $DB_NAME";

# Check if the database exists
!system qq(psql -l | grep -w $DB_NAME | wc -l > $TEMP_DIR/dbexists) or die $!;

open INFILE, "<", "$TEMP_DIR/dbexists" or die $!;
$dbExists = <INFILE>;
$dbExists =~ s/\s+$//;
close INFILE;
!system qq(rm -f $TEMP_DIR/dbexists) or die $!;

if( $dbExists > 0 )
{
  !system qq( dropdb $DB_NAME > /dev/null) or die $!;
}
!system qq( createdb $DB_NAME > /dev/null) or die $!;
println "Database created";

# Create the database schema
println "Creating database schema";
!system qq(psql -U $USERNAME -d $DB_NAME -f sql/create_schema.sql > /dev/null) or die $!;
!system qq(psql -U $USERNAME -d $DB_NAME -f sql/add_pheno_constraints.sql > /dev/null) or die $!;
!system qq(psql -U $USERNAME -d $DB_NAME -f sql/add_anno_constraints.sql > /dev/null) or die $!;
println "Schema is created";

